import Vue from 'vue';

export const Account = {
  async register (username, password, email) {
    let data = await Vue.prototype.$axios.post(`api/account/register`, { username, password, email });
    return !!data;
  },
  async login (account, password, store) {
    let data = await Vue.prototype.$axios.post(`api/account/login`, { account, password });
    setToken('access', data.token);
    setUsername(store, data.username);
    return !!data;
  },
  logout (store) {
    clearToken('access');
    resetUsername(store);
  },
  async follow (username, follow) {
    let data = await Vue.prototype.$axios.post(`api/account/follow`, { username, follow });
    return !!data;
  },
  async uploadVideo (video, cover, title, description) {
    let data = await Vue.prototype.$axios.post(
      `api/account/upload/new`,
      { video, cover, title, description });
    return data;
  }
}

export function setToken (name, token) {
  localStorage.setItem(`${name}Token`, token);
}

export function getToken (name) {
  return localStorage.getItem(`${name}Token`);
}

export function clearToken (name) {
  localStorage.removeItem(`${name}Token`);
}

export function setUsername (store, username) {
  localStorage.setItem('username', username);
  store.commit('user/updateUsernameState', username);
}

export function getUsername() {
  return localStorage.getItem('username');
}

export function resetUsername (store) {
  localStorage.removeItem('username');
  store.commit('user/resetUsernameState');
}
